package com.hs.pre.init;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.hs.Environment;
import com.hs.HsBase;
import com.hs.core.action.BaseAction;
import com.hs.log.HsLogger;
import com.hs.pre.db.InitDatabaseData;
import com.hs.pre.model.PreEntry;
import com.hs.pre.module.sort.InitSortData;
import com.hs.utils.HsUtil;
import com.hs.utils.Utilities;

public class UploadAction extends BaseAction{
	private static final HsLogger logger = HsLogger.getLogger(UploadAction.class.getName());
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception { 
		InitSortData init = new InitSortData();
		boolean flag = init.isExsit(HsBase.getAnsiSqlMap().get("presort.count")+"");
		String filepath = Utilities.getDbRoot().getParent() + System.getProperty("file.separator")+"data";
		Iterator iterator = HsUtil.processMultipartRequest(request, filepath, Environment.getLongValue(Environment.PROP_FILE_MAX_FILE_SIZE));
		String fileFullPath = filepath + System.getProperty("file.separator");
		 
		File uploadedFile = null;
		String fileName = null;
		String fileFllName = null; 
		while (iterator.hasNext()) {
			FileItem item = (FileItem)iterator.next();  
			if (!item.isFormField()) {
				fileName = sanitizeFilename(item.getName());
				fileFllName = System.currentTimeMillis() + "_" +  fileName;
				uploadedFile = new File(fileFullPath  + fileFllName);
				item.write(uploadedFile);
			}
		} 
		
		if(null != fileFllName){
			//解析并写入数据库
			InitDatabaseData fangjiinit = new InitDatabaseData();
			List preList = fangjiinit.readData(fileFllName);
			int allCount = preList.size();
			int successNum = 0;
			if(null != preList){
				for(int i=0;i<preList.size();i++){
					PreEntry entry = (PreEntry)preList.get(i);
					try{
						fangjiinit.insertPre(HsBase.getAnsiSqlMap().get("preinfo.insert")+"", entry);
						entry.initJob();
						successNum++;
					}catch(Exception e){
						System.out.println("新增方剂异常" + entry);
						continue;
					}
				}
			} 
			request.setAttribute("successNum", successNum+"");
			request.setAttribute("allNum", allCount+"");
		}
		
		return mapping.findForward("success");
	}
	private  String sanitizeFilename(String filename) {
		if (StringUtils.isBlank(filename)) {
			return null;
		}
		// some browsers set the full path, so strip to just the file name
		filename = FilenameUtils.getName(filename);
		filename = StringUtils.replace(filename.trim(), " ", "_");
		return filename;
	}
}
